package com.changfeng.service.impl;

import com.changfeng.auth.dto.UserAuth;
import com.changfeng.bean.RetailersOrder;
import com.changfeng.bean.RetailersUser;
import com.changfeng.common.CurrentUser;
import com.changfeng.dao.RetailersOrderMapper;
import com.changfeng.dao.RetailersUserMapper;
import com.changfeng.exception.ChangFengException;
import com.changfeng.exception.ChangFengExceptionEnum;
import com.changfeng.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class PayServiceImpl implements PayService {

    @Autowired
    private RetailersUserMapper retailersUserMapper;

    @Autowired
    private RetailersOrderMapper retailersOrderMapper;

    @Override
    public int payOrder(int orderId) {
        RetailersOrder retailersOrder = retailersOrderMapper.selectByPrimaryKey(orderId);
        UserAuth currentUser = CurrentUser.getCurrentUser();
        Integer userId = currentUser.getUserId();
        RetailersUser retailersUser = retailersUserMapper.selectByPrimaryKey(userId);
        if (retailersUser.getUserIntegral().compareTo(retailersOrder.getOrderPrice()) == -1) {
            throw new ChangFengException(ChangFengExceptionEnum.ERROR).setMessage("金额不足");
        }
        BigDecimal subtract = retailersUser.getUserIntegral().subtract(retailersOrder.getOrderPrice());
        retailersUser.setUserIntegral(subtract);
        retailersUserMapper.updateByPrimaryKey(retailersUser);
        retailersOrder.setOrderState("yfk");
        retailersOrderMapper.updateByPrimaryKey(retailersOrder);
        return retailersOrder.getOrderId();
    }
}
